package zk_01.zookeeper.sample;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.zookeeper.AsyncCallback.StringCallback;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

public class TaskUnSyn implements Watcher{

	private static Logger logger = Logger.getLogger(TaskUnSyn.class);
	private String hostPort ;
	private ZooKeeper zk;
	
	public static void main(String[] args) {
		TaskUnSyn taskClient = new TaskUnSyn("192.168.1.113:2181");
		//TaskUnSyn taskClient = new TaskUnSyn("10.40.12.196:2181");
		try {
			taskClient.startZK();
			for(int i=1;i<=10;i++){
				taskClient.pushTask("今天拍第"+i+"个段子");
				Thread.sleep(1000);
			}
			Thread.sleep(1500000);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	StringCallback pushTaskCallback = new StringCallback(){

		public void processResult(int rc, String path, Object ctx, String name) {
			switch(Code.get(rc)){
			case CONNECTIONLOSS:
				//这种处理有点简单，可能任务已经PUSH成功，再次调用会出现同一个任务多次提交
				pushTask((String)ctx);
				break;
			case OK:
				logger.info(ctx+" was pushed success,taskName is:"+name);
				break;
			default:
				logger.info(ctx+" was pushed unsuccess");
				break;
			}
		}
		
	};
	
	public void pushTask(String task){
		zk.create("/tasks/task-", task.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL, pushTaskCallback, task);
	}
	
	public void process(WatchedEvent event) {
		System.out.println(event);
	}

	public TaskUnSyn(){}
	
	public TaskUnSyn(String hostPort){
		this.hostPort=hostPort;
	}
	
	public void startZK() throws IOException{
		zk = new ZooKeeper(hostPort,15000,this);
	}
	
	public void stopZK() throws InterruptedException{
		zk.close();
	}
}
